<?php

namespace App\Http\Services\Messages;

use App\Http\Services\WechatService;
use App\Models\TemplateAccept;
use App\Repositories\WechatRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class SendMessageService
{
    /**
     * 消息发送
     * @param weapp_openid   小程序openid
     * @param type           模板编号
     * @param data           参数
     */
    public function send($weappOpenId, $type, $params, $msg_type = null)
    {
        if (empty($weappOpenId) || empty($type))
            return false;

        $template_id = TemplateAccept::getTmpId($type);
        if (empty($template_id))
            return false;

        $data = $this->_msg_tpl($msg_type ?? $type, $params);
        if (empty($data))
            return false;

        //检查是否具有权限
        $exist = DB::table("template_accept as ta")
            ->join("member as m", "m.id", "ta.uid")
            ->where("m.weapp_openid", $weappOpenId)
            ->whereNull("ta.deleted_at")
            ->first(['ta.id', 'm.username', 'ta.uid', 'm.openid']);

        if (empty($exist))
            return false;

        $res = (new WechatRepository())->sendSubscribeMessage($template_id, $weappOpenId, $data['pagepath'] ?? '', $data['params'] ?? []);
        $fun = $res['errcode'] == 0 ? 'info' : 'error';

        $data['openid'] = $exist->openid;
        $log_str = '发送人昵称：' . $exist->uid . ' ' . $exist->username . ',' . TemplateAccept::getTitle($type) . ',' . ($res['errcode'] ?? 0) . '_' . ($res['errmsg'] ?? "") . ', params: ' . json_encode($data);
        Log::channel("subscribe")->$fun($log_str);
        if ($res['errmsg'] === 0) {
            (new WechatService())->handleSubscribeMsg($type, $params);
            return true;
        }

        if ($res['errcode'] === 43101) {
            if (!empty($params['uid'])) {
                TemplateAccept::query()->where(['uid' => $params['uid'], 'template_id' => $template_id])->delete();
            }
            return false;
        }

        /*
        Log::channel("subscribe")->info([
            'errcode' => $res['errcode'] ?? 0,
            'errmsg' => $res['errmsg'] ?? '',
            'template_id' => $template_id,
            'weapp_open_id' => $weappOpenId
        ]);
        */

        return true;
    }

    /**
     * 返回模板对应的消息
     * @param int $type
     * @param null $data
     * @return [ 'pagepath' => "", 'params' => []]
     */
    private static function _msg_tpl(int $type, $data = null)
    {
        if (empty($type))
            return false;

        $msgTypes = [
            1 => [//访客
                'pagepath' => $data['page'] ?? 'member-visit/index',
                'params' => [
                    'name1' => $data['username'],
                    'date2' => date("Y-m-d H:i:s"),
                    'thing3' => $data['title'] ?? "访客来访",
                    'thing4' => "Ta在你的主页停留了许久，快去看看吧!",
                ],
            ],

            2 => [
                'pagepath' => "nearby-recommend/member",
                'params' => [
                    'number1' => "10",
                    'thing2' => "附近的人已更新",
                    'thing3' => "有效期24小时，请及时联系，点击查看详情",
//                    'thing3' => "有效期24小时",
                ]
            ],

            10005 => [
                "pagepath" => $data['page'],
                'params' => [
                    'thing1' => $data['username'],
                    'thing2' => $data['uid'] . get_short("号" . "将你移入" . $data['elect_pool_title'] . "互选池心动区。", 20), //适合意向
//                    'thing2' => $data['uid'] . "号" . "将你移入心动区啦，点击进入" . $data['elect_pool_title'] . "互选池被选区查看吧！若被选区没有说明已互选成功或对方已经取消了选择！", //适合意向
                    'time3' => date("Y-m-d H:i"),//联系时间
                    'thing4' => "若将对方也移入心动区即互选成功！",//备注 头像或生活照是真人但非本人的被投诉要扣账户余额！ 警惕交友背后的投资理财博彩诈骗【杀猪盘】，回复“骗子”了解骗子套路!
                ]
            ],

            10006 => [ // 互选池-互选成功
                "pagepath" => $data['page'],
                'params' => [
//                    'thing1' => $data['toUid'] . "号" . $data['toUsername'],
                    'thing1' => $data['content'],
                    'phrase2' => "互选成功",
//                    'phrase2' => "恭喜你互选成功，点击进入" . $data['elect_pool_title'] . "互选池互选成功页面查看吧！扣账户余额" . $data['price'] . "联谊币。当前账户余额为【" . $data['balance'] . "】。若互选成功页面没有该嘉宾信息，说明Ta已取消选择！联系方式互相可见。", //适合意向
                ]
            ],

            100061 => [ // 超级心动
                "pagepath" => $data['page'],
                'params' => [
                    'thing1' => $data['uid'] . "号通过超级心动解锁了你的联系方式。",
                    'phrase2' => "超级心动",
                ]
            ],
        ];

        return $msgTypes[$type] ?? "";
    }

}
